using System;
using System.Configuration;
using System.Configuration.Provider;

namespace Se.Framework.Common.Config.Providers
{
    public static class TypeProviderManager
    {
        private static readonly object oSync = new object();
        private static string defaultName;
        private static TypeProviderCollection collection;

        static TypeProviderManager()
        {
            Initialize();
        }

        private static void Initialize()
        {
            lock (oSync)
            {
                collection = new TypeProviderCollection();
                var providersConfiguration = (TypeProviderConfiguration)ConfigurationManager.GetSection("typeProviders");
                defaultName = providersConfiguration.DefaultProviderName;
                foreach (ProviderSettings providerConfig in providersConfiguration.Providers)
                {
                    var type = Type.GetType(providerConfig.Type);
                    var aProvider = (ProviderBase)Activator.CreateInstance(type);
                    aProvider.Initialize(providerConfig.Name, providerConfig.Parameters);
                    collection.Add(aProvider);
                }
            }
        }

        public static TypeProviderBase Default
        {
            get
            {
                return collection[defaultName];
            }
        }

        public static TypeProviderCollection Collection
        {
            get
            {
                return collection;
            }
        }
    }
}